package com.work.module_base.httpretrofit;


import com.work.module_base.utils.JsonUtils;
import com.work.module_base.utils.LogUtils;
import com.work.module_base.utils.UIUtils;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Aly on 2016/9/18.
 * Retrofit 请求回调
 */
public abstract class MyCallback<T> implements Callback<T> {
    /**
     * 成功
     */
    public void onResponse(Call<T> call, Response<T> response) {
        if (response.isSuccessful()) {
            String json = JsonUtils.parseBeantojson(response.body());
            LogUtils.d("----数据解析成功----");
            LogUtils.d("onSuccess:" + json);
            onSuccess(response.body());
            onComplete();
        } else {
            ResponseBody responseBody = response.errorBody();
            try {
                String errMsg = responseBody.source().readUtf8().toString();
                LogUtils.d("onFailer:" + errMsg);
                onFailure(1111111, errMsg);
            } catch (IOException e) {
                e.printStackTrace();
            }
            onComplete();
        }
    }

    /**
     * 失败
     */
    @Override
    public void onFailure(Call<T> call, Throwable t) {
        // TODO: 2016/9/18 网络错误
        LogUtils.e("onFailure===:" + t.getMessage());

        if (t.getMessage().contains("Unable to resolve host")) {
            UIUtils.showToast("服务器链接失败,请稍后重试");
        } else {
            HttpStatus httpStatus = JsonUtils.parseJsonToBean(t.getMessage(), HttpStatus.class);
            if (httpStatus != null) {
                UIUtils.showToast(httpStatus.getMsg());
                onFailure(httpStatus.getStatus(), httpStatus.getMsg());
            } else {
                onFailure(1111111, "未知错误");
            }
        }
        onComplete();
    }

    //接口通过200 返回的
    public abstract void onSuccess(T response);

    //接口未通过
    public abstract void onFailure(int errorCode, String errMsg);

    //接口完成(通过和未通过)
    public abstract void onComplete();

}
